package main

import (
	hello "04-grpc-metadata/proto"
	"context"
	"log"

	// "time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	// "google.golang.org/grpc/metadata"
)

type customCredential struct{}

func (c customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (customMeta map[string]string, err error) {
	customMeta = map[string]string{
		"name": "Bob",
		"pwd":  "123456",
	}
	return
}

func (c customCredential) RequireTransportSecurity() bool {
	return false
}

func main() {
	// clientInterceptor := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	// 	start := time.Now()
	// 	md := metadata.New(map[string]string{
	// 		"name": "Bob",
	// 		"pwd":  "123456",
	// 	})
	// 	ctx = metadata.NewOutgoingContext(ctx, md)
	// 	err := invoker(ctx, method, req, reply, cc, opts...)
	// 	log.Println("请求耗时:", time.Since(start))
	// 	return err
	// }

	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	// opts = append(opts, grpc.WithUnaryInterceptor(clientInterceptor))
	opts = append(opts, grpc.WithPerRPCCredentials(customCredential{}))

	conn, err := grpc.NewClient("0.0.0.0:3005", opts...)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	c := hello.NewHelloClient(conn)

	r, err := c.SayHello(context.Background(), &hello.HelloReq{
		Name: "Bob",
	})
	if err != nil {
		panic(err)
	}

	log.Println(r.Data, r.Time)
}
